<template>
	<div class="app-container" v-loading="loading" @contextmenu.prevent="">
		<div class="search-container  app_ny">
			<div class="div2" style="position: relative">
				<el-row :gutter="12" style="width: 100%">
					
					<el-col :span="4">
						<el-tree-select  style="width: 100%;"
							placeholder="请选择所属公司" 
							v-model="queryParams.cid" 
							:data="baseConfigStore.newExCompanyList"
							:render-after-expand="false"
							 :default-expand-all="true" 
							 check-strictly clearable
							@node-click="nodeClickCompany" 
							@clear="nodeClearCompany">
							<template v-slot:default="{node, data }">
								<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
							</template>
						</el-tree-select>
					</el-col>
					<el-col :span="3">
						<el-select 
							v-model="queryParams.sid" 
							@change="nodeClick"
							placeholder="请选择仓库"
							clearable>
							<el-option v-for="item in stockList" :key="item.id" :label="item.name"
								:value="item.id" />
						</el-select>
					</el-col>
					
					<!-- <el-col :span="4">
						<el-tree-select placeholder="请选择仓库" v-model="queryParams.sid" clearable :data="stockList"
							:render-after-expand="false" :default-expand-all="true" @node-click="nodeClick">
							<template v-slot:default="{node, data }">
								<treeBlock :nodeItem="node" :dataItem="data" :typeClass="3"></treeBlock>
							</template>
						</el-tree-select>
					</el-col> -->
					<el-col :span="3">
						<el-select v-model="queryParams.pid" placeholder="请选择存放位置" clearable>
							<el-option v-for="item in positionCell" :key="item.id" :label="item.name"
								:value="item.id" />
						</el-select>
					</el-col>
					<el-col :span="3">
						<el-input v-model="queryParams.name" placeholder="请输入物品名称" clearable />
					</el-col>
					<el-col :span="7">
						<el-button :loading="loading" type="primary" @click="handleQuery">
							<template #icon><i-ep-search /></template>查询</el-button>
					</el-col>
				</el-row>
				<FilterColumn class="filtBox" @handleRefresh="resetQuery()" :strtype="strtype"></FilterColumn>
			</div>
		</div>

		<el-card shadow="never">
			<div class="action-row">
				<el-button v-hasPerm="['wms.Stock/log']" @click="handleDo('','act_change')" :disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)" plain><template
						#icon><i-ep-plus /></template>变更记录</el-button>

			</div>
			
			<el-table 
				ref="dataTableRef" 
				v-loading="loading" 
				:data="tableData" align="left"
				tooltip-effect="dark" 
				:scrollbar-always-on="true" 
				:show-overflow-tooltip="true" border
				@cell-mouse-enter="rowMouse"
				@cell-mouse-leave="menuLineVisible=false"
				 @selection-change="handleSelectionChange">
				<el-table-column type="selection" align="center" width="55" />
				<el-table-column type="index" label="序号" align="center" width="80" />
				<template v-for="(item,index) in cColumnsList()" :key='index'>
					<el-table-column :label="item.label" :align="item.align" :prop="item.prop" :width="item.width" :min-width="item.minwidth">
						<template #default="scope" v-if="item.prop == 'goods.image'">
							<el-image style="width: 50px; height: 50px" :src="scope.row.goods.image" :zoom-rate="1.2"
								:max-scale="7" :min-scale="0.2" :preview-src-list="[scope.row.goods.image]"
								:initial-index="0" fit="cover" />
						</template>

						<template #default="scope" v-if="item.prop == 'num'">
							<el-text :type="scope.row.num >0? 'Primary':'danger'">{{scope.row.num}}</el-text>
						</template>
					</el-table-column>
				</template>

				
			</el-table>

			<pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
				v-model:limit="queryParams.limit" @pagination="handleQuery" />
		</el-card>

		<!-- 变更记录 -->
		<!-- <financingEdit ref="financingEditRef" @initRefreshList="handleQuery"></financingEdit> -->
		<ChangeRecord ref="changeRecordRef" @initRefreshList="handleQuery" :dataPar="parmeter"></ChangeRecord>

		<!-- <el-dialog v-model="dialogAdd.visible" title="变更记录" :destroy-on-close="true" :fullscreen="true">
			<ChangeRecord :dataPar="parmeter"></ChangeRecord>
		</el-dialog> -->
	</div>
</template>
<script setup lang="ts">
	defineOptions({
		name: "Stockroom",
		inheritAttrs: false,
	});
	import ChangeRecord from "./ChangeRecord.vue"
	//接口地址
	import {
	
		getPositionOptions,
		getStockList,
		getStockroomSelectList
	} from "@/api/wms";


	import { useTableFilterStore } from "@/store/modules/tableFilter";
	import { useBaseConfigStore } from "@/store/modules/baseConfig";
	const baseConfigStore = useBaseConfigStore();
	const TableFilter = useTableFilterStore();
	const strtype = ref('vmsStock')

	// 表格标题
	const cTitles = ["图片", "物品名称", "编码", "所属公司", "品牌", "规格型号","单位", "物料号","备注","仓库", "仓位", "库存数量"];
	// 显示字段
	const sTitles = ["图片", "物品名称", "所属公司", "仓库", "仓位", "库存数量"];
	// 字段属性	
	const cColumns = [
		{ label: "图片", prop: "goods.image", align: "center", width: 80 },
		{ label: "物品名称", prop: "goods.name", align: "center", minwidth: 150 },
		{ label: "批次号", prop: "goods.part_no", align: "center", minwidth: 150 },
		{ label: "编码", prop: "goods.sku", align: "center", minwidth: 150 },
		{ label: "所属公司", prop: "company.name", align: "center", minwidth: 200 },
		{ label: "物料号", prop: "goods.part_no", align: "center", minwidth: 150 },
		{ label: "品牌", prop: "goods.brand", align: "center", minwidth: 150 },
		{ label: "规格型号", prop: "goods.specs", align: "center", minwidth: 150 },
		{ label: "单位", prop: "goods.unit", align: "center", minwidth: 150 },
		{ label: "备注", prop: "goods.mark", align: "center", minwidth: 150 },
		{ label: "仓库", prop: "stockroom.name", align: "center", minwidth: 150 },
		{ label: "仓位", prop: "position.name", align: "center", minwidth: 150 },
		{ label: "库存数量", prop: "num", align: "center", width: 120 },
	]
	interface TableGlobalLocal {
		[key : string] : any; // 或者更具体的类型
	}
	// 列表渲染
	function cColumnsList() {
		const ColumnsList = (TableFilter.tableGlobalLocal as TableGlobalLocal)[strtype.value + '_checklist'];
		if (ColumnsList) {
			const columnMap : any = {}; // 创建一个对象来存储cColumns中label和对象的映射  
			// 预先建立label到对象的映射  
			for (const column of cColumns) {
				columnMap[column.label] = column;
			}
			const newList = [];
			for (const label of ColumnsList) {
				// 尝试从映射中获取对象  
				const foundColumn = columnMap[label];
				if (foundColumn) {
					// 如果找到了，则添加到newList中  
					newList.push(foundColumn);
				}
			}
			return newList;
		}
		else {
			return [];
		}
	};
	// 列表-数据列初始化
	function columnsInit() {
		const dropColStr : string = strtype.value + '_dropCol';
		const checklistStr : string = strtype.value + '_checklist';
		const drop_col : any = (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[dropColStr];
		const checklist = (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[checklistStr];
		if (!drop_col) {
			(TableFilter.tableGlobalLocal as TableGlobalLocal)[dropColStr] = JSON.parse(JSON.stringify(cTitles));
			(TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[dropColStr] = JSON.parse(JSON.stringify(cTitles));
		}
		if (!checklist) {
			(TableFilter.tableGlobalLocal as TableGlobalLocal)[checklistStr] = JSON.parse(JSON.stringify(sTitles));
			(TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[checklistStr] = JSON.parse(JSON.stringify(sTitles));
		}
	}

	const changeRecordRef = ref();//变更列表
	//m默认搜索字段
	const queryParamsData = {
		page: 1,
		limit: 20,
		cid: "",//公司
		sid: "",//仓库
		pid: "",//仓位id
		name: ""//物品名称
	}
	//搜索-字段配置
	const queryParams = reactive(JSON.parse(JSON.stringify(queryParamsData)));
	
	const parmeter = ref<any>({
		cid: "", //公司id
		sid: "", //仓库id
		gid: "", //物品id
		position_id: "" //仓位 id
	})
	const stockList = ref<any>();
	const positionCell = ref<any>()
	const loading = ref(false);
	const total = ref(0);
	const tableData = ref();
	const multipleSelection = ref<any>([]);
	const menuLineVisible = ref(true);
	const rowR = ref<any>({});
	
	const dialogAdd = reactive<any>({
		visible: false,   //弹窗显示or隐藏
		title: "", //弹窗标题
		status: "", //弹窗状态类型  :添加 add_art 编辑 edit_art 详情 detail_art  
		value: {}
	});
	
	// 行菜单事件
	function rowMouse(row : any) {
		menuLineVisible.value = true
		rowR.value = row
	}
	// 数据多选事件
	function handleSelectionChange(val : any) {
		multipleSelection.value = val
	}
	// 操作按钮样式
	function buttonType(val : number) {
		if (val === 1) {
			return 'primary'
		} else {
			return 'info'
		}
	}
	
	// 操作
	function handleDo(row : any, act : string) {
		let uItem : any = {}
		dialogAdd.status = act
		switch (act) {
			case 'act_change':
					uItem = JSON.parse(JSON.stringify(row || multipleSelection.value[0]))
					dialogAdd.visible = true;
					dialogAdd.title = '变更记录';
					changeRecordRef.value.handleShow(row || multipleSelection.value[0], act)
				break
			default:
		}
	}
	
	
	
	


	//获取仓库信息列表
	function handleQuery() {
		loading.value = true;
		console.log(queryParams)
		getStockList(queryParams).then((res) => {
			console.log(res);
			tableData.value = res.data.list;
			total.value = res.data.count;
		}).finally(() => {
			loading.value = false;
		})
	}
	/**
	 * 重置查询
	 */
	function resetQuery() {
		handleQuery();
	}

	// 获取options 配置项
	function get_options() {
	
	}
	function nodeClick(sid : any) {
		queryParams.sid = sid;
		getPositionList(sid);
	}
	/**
	 * 获取仓位
	 */
	function getPositionList(sid : any) {
		getPositionOptions({
			sid: sid
		}).then((res) => {
			queryParams.pid = ""
			positionCell.value = res.data;
		}).finally(() => { })
	}
	// 选择公司id
	function nodeClickCompany(a : any, b : any, c : any, d : any) {
		queryParams.sid = "";
		initStockList(a.cid)
	}
	// 取消选择公司id
	function nodeClearCompany() {
		stockList.value = [];
		queryParams.sid = "";
	}
	/**获取仓库列表 */
	function initStockList(cid ?: number) {
		getStockroomSelectList({ cid: cid }).then((res) => {
			stockList.value = res.data;
		}).finally(() => { })
	}
	
	
	onMounted(() => {
		handleQuery();
		columnsInit();
		get_options();
	})
</script>



<style scoped>
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	.min220 {
		width: 220px
	}
</style>

<style>
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}
</style>